<template>
	<view class="pageBody">
		<view class="mycanvasBody bgf" style="width: calc(95vw - 100rpx); height: 90vh">
			<view class="tipsBox" :style="{opacity: showTips ? 1 : 0}">
        <u-icon name="edit-pen-fill" size="32" color="#999"></u-icon>
        <view class="tipsTitle">请在当前区域内签名</view>
      </view>
			<canvas
				class="mycanvas"
				style="width: calc(95vw - 100rpx); height: 90vh"
				canvas-id="mycanvas"
				@touchstart="touchstart"
				@touchmove="touchmove"
				@touchend="touchend"
			></canvas>
		</view>
		<view style="width: 100rpx; height: 90vh" class="pl-5 _btnBox">
			<u-button
				:customStyle="{
					height: '48%',
				}"
				text="重 写"
        @click="clear"
			></u-button>
			<u-button
				:customStyle="{
					height: '48%',
				}"
				type="primary"
				text="提 交"
        :throttleTime="500"
        @click="confirm"
			></u-button>
		</view>
	</view>
</template>

<script>
import uploadFile from "@/utils/obsutil/uploadFile";
import expApi from "@/api/expertIdentity.js"

export default {
	data() {
		return {
      showTips: true, // 是否显示画布提示

			ctx: "", //绘图图像
			points: [], //路径点集合
			signature: "",
		};
	},
	mounted() {
    const that = this;
		//创建绘图对象
		that.ctx = uni.createCanvasContext("mycanvas", this);
		//设置画笔样式
		that.ctx.lineWidth = 4;
		that.ctx.lineCap = "round";
		that.ctx.lineJoin = "round";
    // 设置背景颜色
    const query = uni.createSelectorQuery().in(this);
    query.select('.mycanvas').boundingClientRect((res)=>{
      that.ctx.setFillStyle('#FFFFFF')
      that.ctx.fillRect(0, 0, Math.ceil(res.width), Math.ceil(res.height))
    }).exec();
	},
	methods: {
		//触摸开始，获取到起点
		touchstart(e) {
      this.showTips = false;
			let startX = e.changedTouches[0].x;
			let startY = e.changedTouches[0].y;
			let startPoint = {
				X: startX,
				Y: startY,
			};
			this.points.push(startPoint);
			//每次触摸开始，开启新的路径
			this.ctx.beginPath();
		},
		//触摸移动，获取到路径点
		touchmove(e) {
			let moveX = e.changedTouches[0].x;
			let moveY = e.changedTouches[0].y;
			let movePoint = {
				X: moveX,
				Y: moveY,
			};
			this.points.push(movePoint); //存点
			let len = this.points.length;
			if (len >= 2) {
				this.draw(); //绘制路径
			}
		},
		// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
		touchend() {
			this.points = [];
		},
		/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
		draw() {
			let point1 = this.points[0];
			let point2 = this.points[1];
			this.points.shift();
			this.ctx.moveTo(point1.X, point1.Y);
			this.ctx.lineTo(point2.X, point2.Y);
			this.ctx.stroke();
			this.ctx.draw(true);
		},
		//清空画布
		clear() {
			const that = this;
			uni.getSystemInfo({
				success: function (res) {
					let canvasw = res.windowWidth;
					let canvash = res.windowHeight;
					that.ctx.clearRect(0, 0, canvasw, canvash);
					that.ctx.draw(true);
          that.showTips = true;
				},
			});
		},
		//完成绘画并保存到本地
		confirm() {
			const that = this;
      if(that.showTips){
        uni.showToast({
          title: '请书写签名后再提交哦!',
          icon: 'none'
        })
        return
      }
      const currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
      const backUrl = currentRoutes[currentRoutes.length - 2]?.route;
			uni.canvasToTempFilePath({
				canvasId: "mycanvas",
				success: function (res) {
          uploadFile(res.tempFilePath, ".png", (url) => {
            expApi.setSetUp({type: 2, value: url}).then(_r =>{
              if(backUrl === 'expertIdentity/prescription/audit'){
                console.log('是订单详情进入签名,返回则刷新订单详情');
                that.$store.commit("SET_ISRESET", true);
              }
              that.goBack()
            })
          });
				},
        fail: function (err) {
          console.log(err,'canvas保存失败');
        }
			});
		},
	},
};
</script>

<style lang="scss" scoped>
.pageBody {
	width: 100vw;
	height: 100vh;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #f5f5f5;
}
.mycanvasBody {
	border: dashed 1px #e2e2e2;
	border-radius: 8rpx;
	overflow: hidden;
  position: relative;
  .tipsBox{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    .tipsTitle{
      font-size: 16px;
      color: #999999;
    }
  }
}

._btnBox {
	flex-shrink: 0;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: space-between;
}
.blockNone{
  display: none;
}
</style>
